﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.Unit
{
    public class EnumHelper
    {
        /// <summary>
        /// 将枚举转成列表
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static Dictionary<string, int> ToList(Type en)
        {
            Dictionary<string, int> list = new Dictionary<string, int>();
            foreach (int i in Enum.GetValues(en))
            {
                list.Add(Enum.GetName(en, i), i);
            }
            return list;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static int All(Type en)
        {
            int k = 0;
            foreach (int i in Enum.GetValues(en))
            {
                k = (k | i);
            }
            return k;
        }

        /// <summary>
        /// 将枚举转成表格（name,value两列）
        /// </summary>
        /// <param name="en">必须为枚举类型</param>
        /// <returns></returns>
        public static DataTable ToTable(Type en)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            //foreach (int v in Enum.GetValues(en)) dt.Rows.Add(Enum.GetName(en, v), v);
            //按枚举定义顺序
            foreach (var v in en.GetFields())
            {
                if (v.FieldType.IsEnum)
                {
                    dt.Rows.Add(v.Name, v.GetRawConstantValue());
                }
            }
            return dt;
        }

        /// <summary>
        /// 将枚举转成JS数组
        /// </summary>
        /// <param name="en">必须为枚举类型</param>
        /// <param name="arrayName">数组名称</param>
        /// <returns></returns>
        public static string ToJsArray(Type en)
        {
            string s = "[";
            foreach (int v in Enum.GetValues(en))
            {
                s += (s == "[" ? "" : ",") + "[\"" + Enum.GetName(en, v) + "\",\"" + v.ToString() + "\"]";
            }
            return s + "]";
        }

        /// <summary>
        /// 将多个枚举值用指定符号拼接起来
        /// </summary>
        /// <param name="operate"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        public static string Join(string operate, params ValueType[] v)
        {
            string s = "";
            for (int i = 0; i < v.Length; i++)
            {
                s += operate + ((int)v[i]).ToString();
            }
            return s.TrimStart(',');
        }

        /// <summary>
        /// 将多个枚举值用逗号拼接起来
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public static string Join(params ValueType[] v)
        {
            return Join(",", v);
        }        
        
    }
}
